<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/**
 * HTML5端 用户中心API文件
 * User: poptser
 * Email:poptser@foxmail.com
 * Date: 2016/8/13
 * Time: 13:45
 */

namespace SDXApi\Model;
use SDXApi\Service\OrderDistributionTimeService;
use Think\Model;
class UsersModel extends Model
{

    protected $tableName = 'users';
    /**
     * 更新用户登录时间、登录次数。
     *
     * @access  public
     * @return  void
     */
    public function update_user_info($uid=null) {
        if ($uid) {
            return false;
        }
        $data = array('last_ip'=>get_ip(),'last_login'=>gmtime());
        $this->where('user_id='.$uid)->setInc('visit_count')->setField($data);
    }

    /**
     * 修改用户来源
     * Created by Jerry
     * @param $user_id
     * @param $is_hd
     * @return bool
     */
    public function update_user_is_hd_by_user_id($user_id, $is_hd)
    {
        if (empty($user_id)) {
            return false;
        }

        $where = array(
            'user_id'	=>	$user_id,
        );

        return $this->where($where)->setField('is_hd',$is_hd);
    }

    /**
     * 用户注册，登录函数
     *
     * @access  public
     * @param   string       $username          注册用户名
     * @param   string       $password          用户密码
     * @param   string       $email             注册email
     * @param   array        $other             注册的其他信息
     *
     * @return  bool         $bool
     */
    public function register($username, $password, $email, $other = array()) {
        /* 检查username */
        if (empty($username)) {
            return false;//用户名为空
        } else {
            if (preg_match('/\'\/^\\s*$|^c:\\\\con\\\\con$|[%,\\*\\"\\s\\t\\<\\>\\&\'\\\\]/', $username)) {
                return false;//用户名是否符合规格

            }
        }
        /* 检查email */
        if (empty($email)) {
            return false;

        } else {
            if (!is_email($email)) {
                return false;

            }
        }
        //检查username是否重复
        if($this->where(array('user_name' => $username))->count()>0){
            return false;//用户名已存在

        }
        $post_password = compile_password(array('password' => $password));


        $add_data['user_name']=$username;
        $add_data['password']=$post_password;
        $add_data['email']=$email;
        $add_data['reg_time']=gmtime();
        $add_data['last_login']=gmtime();
        $add_data['user_rank']=1;

        if(!empty($other['phone'])){
            $add_data['mobile_phone']=$other['phone'];
        }

        if ($this->add($add_data)) {
            //注册成功,返回用户的ID
            return $this->where(array('user_name' => $username))->getField('user_id');
        } else {
            //注册失败
            return false;

        }
    }

    /**
     * 返回会员等级
     * @param $user_id
     * @return mixed
     */
    public function get_user_rank($user_id)
    {

        $where = array(
            'user_id'   =>  $user_id,
        );

        $field = 'user_id, user_rank';

        $data = $this->field($field)->where($where)->find();

        $where =array(
            'rank_id'   =>  $data['user_rank'],
        );
        $rank = M('user_rank')->field('discount')->where($where)->find();

//        折扣计算
        $rank['discount'] = $rank['discount'] / 100;

        return array_merge($rank, $data);
    }

    /**
     * 获取用户名
     * @param null $uid
     * @return bool|mixed
     */
    public function get_user_username($uid=null){
        if(empty($uid)){
            return false;
        }else{
            $username =S($uid."_username");
            if($username){
                return $username;
            }else{
                $username = $this->where(array("user_id"=>$uid))->getField("user_name");
                if($username){
                    S($uid."_username",$username,86400);
                    return $username;
                }else{
                    return false;
                }
            }
        }
    }

    /**
     * 获取用户金额
     * @param null $uid
     * @return bool|mixed
     */
    public function get_user_money($uid=null){
        if(empty($uid)){
            return false;
        }else{
            $user_money = $this->where(array("user_id"=>$uid))->getField("user_money");
            if($user_money){
                return $user_money;
            }else{
                return false;
            }
        }
    }

    /**
     * 获取用户电子邮箱
     * @return bool|mixed
     */
    public function get_user_email($uid){
        if(empty($uid)){
            return false;
        }else{
            $email =S($uid."_email");
            if($email){
                return $email;
            }else{
                $email = $this->where(array("user_id"=>$uid))->getField("email");
                if($email){
                    S($uid."_email",$email);
                    return $email;
                }else{
                    return false;
                }
            }
        }
    }

    /**
     * 获取用户手机号码
     * Created by Jerry
     * @param int $userId
     * @return mixed
     */
    public function findUserPhone($userId = 0)
    {
        $where = array(
            'user_id'   =>  $userId,
        );

        return $this->where($where)->getField('mobile_phone');
    }

    /*设定用户定位
     * location 默认0 0-自动默认取用户默认收货地址来定位,若用户没有设定默认地址，那么必须传经纬度值   1-获取当前手机定位位置
     * long  经度
     * lati  纬度
     * */
    public function set_users_location($uid,$location=0,$long=0,$lati=0){
        $longitude = $long;
        $latitude = $lati;
        $user_id = $uid;
        $hand = $location;
        if(empty($user_id)){
            $hand = true;//无用户ID  使用定位参数
        }

        if($hand){
            if($long && $lati){
                $address = gps_to_address($longitude,$latitude);
                $address_gps['longitude'] = $latitude;
                $address_gps['latitude'] = $longitude;
            }else{
                returnApiError('经纬度参数错误');
            }
        }else{
            $address = $this->get_default_address($user_id);
            if($address){
                $address_gps = address_to_gps_amap($address['all_address'],$address['city']);
                $distribution_data['sign_building'] = $address['sign_building'];
            }else{
                $address_gps['longitude'] = $latitude;
                $address_gps['latitude'] = $longitude;
                $address = gps_to_address($longitude,$latitude);
            }
        }

        $distribution_data = $this->get_distribution_by_gps($address_gps['longitude'],$address_gps['latitude']);
        //dump($distribution_data['is_day']);
        $distribution_data['dis_time']=A("Order")->get_distribution_time(null,$distribution_data['mode_id']);
        $distribution_data['all_address'] = $address['all_address'];
        $distribution_data['lit_address'] = $address['lit_address'];

        //dump($distribution_data);
        if($distribution_data){
            $distribution_data['return'] =1;
        }else{
            $distribution_data['return'] =0;
        }

        if($hand==0 && $address['id']){
            $distribution_data['address_id'] = $address['id'];
        }else{
            $distribution_data['address_id'] = 0;
        }

        return $distribution_data;
    }


    public function get_default_address($uid){
        $address = M('user_address')->where(array('user_id'=>$uid,'default'=>1))->find();

        if($address){
            $address_data = array();

            $province = M('region')->where('region_id ='.$address['province'])->getField('region_name');
            $city = M('region')->where('region_id ='.$address['city'])->getField('region_name');
            $district = M('region')->where('region_id ='.$address['district'])->getField('region_name');
            $address_data['id']=$address['address_id'];
            $address_data['province_name']=$province;
            $address_data['city_name']=$city;
            $address_data['district_name']=$district;
            $address_data['is_default']=$address['default'];

            $all_address = $province.$city.$district.$address['address'];
            $address_data['all_address'] = str_replace(' ','',$all_address);
            $address_data['lit_address'] = $address['address'];
            $address_data['longitude'] =  $address['longitude'];
            $address_data['latitude'] = $address['latitude'];
            $address_data['sign_building'] = $address['sign_building'];
        }

        return $address_data;
    }
    /*
     * 获取用户地址转经纬度
     * */
    public function get_address_conversion($address){
        $res=address_to_gps_amap($address);
        return $res;
    }

    /**
     * 根据经纬度获取区域优惠信息
     * @param $longitude
     * @param $latitude
     * @return mixed
     */
    public function get_distribution_by_gps($longitude, $latitude){
        $wdr_mod=M('warehouse_deliver_region');
        $wdrc_mod=M('warehouse_deliver_region_coordinates');
        $wdr=S('warehouse_deliver_region_data');
        //dump($wdr);
        if(!$wdr){
            $wdr=$wdr_mod->where(array('status'=>1))->select();
            if($wdr){
                S('warehouse_deliver_region_data',$wdr);
            }
        }
        if($wdr){
            $distribution_mode=S('distribution_mode_data');
            if(!$distribution_mode){
                $distribution_mode = M("distribution_mode")->where(array("state"=>0))->select();
                if($distribution_mode){
                    S('distribution_mode_data',$distribution_mode);
                }
            }
            foreach ($wdr as $key=>$val){
                foreach ($distribution_mode as $key2=>$value){
                    if($val['wdtype']==$value['id']){

                        $wdrc=S('warehouse_deliver_region_coordinates_'.$val['id']);
                        if(!$wdrc){
                            $wdrc=$wdrc_mod->field("id,rid,alongitude as longitude,alatitude as latitude")
                                ->where(array('rid'=>$val['id']))->select();
                            if($wdrc){
                                S('warehouse_deliver_region_coordinates_'.$val['id'],$wdrc);
                            }
                        }
                        if ($wdrc){
                            foreach ($wdrc as $k=>$v){
                                $polygon[$value['id']][$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'mode_id'=>$key2,'name'=>$val['name'],'start_price'=>(float)$val['start_price']);
                            }
                        }else {
                            continue;
                        }
                    }
                }
            }
        }else{
            $arr['name'] = -1;
            $arr['price'] = (float)-1;
            $arr['prescription'] = "out of area 1";
            $arr['wid']=C("DEFAULT_WID");
            $arr['is_day']  =   -1;
            $arr['wdr_id']  =   0;
            $arr['mode_id'] =   -1;
            return $arr;
        }
        //dump($polygon);

        foreach ($polygon as $key2=>$value2){
            //所有配送区域方式组
            foreach ($value2 as $key=>$value){
                foreach ($value as $k=>$v){
                    $free[$k]=array('mode_id'=>$v['mode_id'],'lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                }
                $data=$this->isPointInPolygon($free,$longitude,$latitude);
                if($data){
                    $arr['price'] = (float)$free[0]['start_price'];
                    $arr['name'] = "free";
                    $arr['name_true'] = $free[0]['name'];
                    if($distribution_mode[$free[0]['mode_id']]['arrival_type']==0){
                        $arr['prescription'] = "3小时";
                    }else{
                        $arr['prescription'] = "24小时";
                    }
                    $arr['wid']=$free[0]['wid'];
                    $arr['wid_name']=M("warehouse")->where(array("id"=>$free[0]['wid']))->getField("name");
                    $arr['is_day']=$distribution_mode[$free[0]['mode_id']]['arrival_type'];
                    $arr['wdr_id'] = $key;
                    $arr['mode_id'] =  $key2;
                    return $arr;
                }
                unset($free);
                unset($data);
            }
        }

        $arr['name'] = -1;
        $arr['price'] = (float)-1;
        $arr['prescription'] = "out of area 2";
        $arr['wid']=C("DEFAULT_WID");
        $arr['is_day']=-1;
        $arr['wdr_id'] = 0;

        return $arr;
    }


    /**
     * 射线法计算坐标是否在规定图形内
     * @param $polygon
     * @param $longitude
     * @param $latitude
     * @return bool
     */
    public function isPointInPolygon($polygon, $longitude, $latitude){
        $count = count($polygon);
        $px = $longitude;
        $py = $latitude;
        $flag = false;
        for ($i = 0, $j = $count - 1; $i < $count; $j = $i, $i++) {
            $sy = $polygon[$i]['lng'];
            $sx = $polygon[$i]['lat'];
            $ty = $polygon[$j]['lng'];
            $tx = $polygon[$j]['lat'];

            if ($px == $sx && $py == $sy || $px == $tx && $py == $ty)
                return true;

            if ($sy < $py && $ty >= $py || $sy >= $py && $ty < $py) {
                $x = $sx + ($py - $sy) * ($tx - $sx) / ($ty - $sy);
                if ($x == $px)
                    return true;
                if ($x > $px)
                    $flag = !$flag;
            }
        }
        return $flag;
    }

    /**
     * 根据用户ID 获取用户手机号码
     * @param null $uid
     * @return bool|mixed
     */
    public function get_user_phone($uid=null){
        if(empty($uid)){
            return false;
        }else{
            $mobile_phone = S($uid."_user_phone");
            if($mobile_phone){
                return $mobile_phone;
            }else{
                $mobile_phone = $this->where(array("user_id"=>$uid))->getField("mobile_phone");
                if($mobile_phone){
                    S($uid."_user_phone",$mobile_phone,300);
                    return $mobile_phone;
                }else{
                    return false;
                }
            }
        }
    }
    /**
     * 获取用户昵称
     * @param null $uid
     * @return bool|mixed
     */
    public function get_user_nickname($uid=null){
        if(empty($uid)){
            return false;
        }else{
            $nickname =S($uid."_nickname");
            if($nickname){
                return $nickname;
            }else{
                $nickname = M("wechat_user")->where(array("ect_uid"=>$uid))->getField("nickname");
                if($nickname){
                    S($uid."_nickname",$nickname,1800);
                    return $nickname;
                }else{
                    return false;
                }
            }
        }
    }

    /**
     * 根据商品id获取购物车中此id的数量
     */
    public function get_goods_number($goods_id,$uid) {
        $Model=new Model();
        // 查询
        $sql = "SELECT IFNULL(SUM(goods_number), 0) as number " .
            " FROM " . C('DB_PREFIX').
            "cart WHERE user_id = '" . $uid . "' AND rec_type = '" . CART_GENERAL_GOODS . "' AND goods_id = " . $goods_id;
        $res = $Model->query($sql);
        return $res[0]['number'];
    }

    public function get_quota_goods_number($goods_id,$uid){
        $Model=new Model();
        // 查询
        $sql = "SELECT IFNULL(SUM(goods_number), 0) as number " .
            " FROM " . C('DB_PREFIX').
            "cart WHERE user_id = '" . $uid . "' AND rec_type = '" . CART_GENERAL_GOODS . "' AND goods_id = " . $goods_id;
        $res = $Model->query($sql);
        return $res[0]['number'];
    }

    /**
     * 获得订单中的费用信息
     *
     * @access  public
     * @param   array   $order
     * @param   array   $goods
     * @param   array   $consignee
     * @param   bool    $is_gb_deposit  是否团购保证金（如果是，应付款金额只计算商品总额和支付费用，可以获得的积分取 $gift_integral）
     * @return  array
     */
    public function order_fee($order, $goods, $consignee) {
        /* 初始化订单的扩展code */
        if (!isset($order['extension_code'])) {
            $order['extension_code'] = '';
        }

        if ($order['extension_code'] == 'group_buy') {
            $group_buy = D('Goods')->group_buy_info($order['extension_id']);
        }

        $total = array(
            'real_goods_count' => 0,
            'gift_amount' => 0,
            'goods_price' => 0,
            'market_price' => 0,
            'discount' => 0,
            'pack_fee' => 0,
            'card_fee' => 0,
            'shipping_fee' => 0,
            'shipping_insure' => 0,
            'integral_money' => 0,
            'bonus' => 0,
            'surplus' => 0,
            'cod_fee' => 0,
            'pay_fee' => 0,
            'tax' => 0
        );
        $weight = 0;
        $Model =new Model();
        /* 商品总价 */
        foreach ($goods AS $val) {
            /* 统计实体商品的个数 */
            if ($val['is_real']) {
                $total['real_goods_count'] ++;
            }


            //        折扣满减 第二件半价
//            $favourableModel = D('FavourableActivity');
//            $discount = $favourableModel->check_discount_by_goods_id_set_price($val['user_id'], $val['goods_id'], $val['goods_number']);
//            if(!empty($discount)){
////                $val['goods_price'] = $discount['price'];
////                $total['benefit_price'] += $discount['benefit_price'];
//                $total['discount'] += $discount['benefit_price'];
//            }


            $total['goods_price'] += $val['goods_price'] * $val['goods_number'];
            $total['market_price'] += $val['market_price'] * $val['goods_number'];
        }

        $total['saving'] = $total['market_price'] - $total['goods_price'];
        $total['save_rate'] = $total['market_price'] ? round($total['saving'] * 100 / $total['market_price']) . '%' : 0;

        $total['goods_price_formated'] = price_format($total['goods_price'], false);
        $total['market_price_formated'] = price_format($total['market_price'], false);
        $total['saving_formated'] = price_format($total['saving'], false);

        /* 折扣 */
        if ($order['extension_code'] != 'group_buy') {
            $discount = D('Cart')->compute_discount();
//            dd($discount);
            if($discount['discount'] > 0){
                $total['discount'] = $discount['discount'];
                if ($total['discount'] > $total['goods_price']) {
                    $total['discount'] = $total['goods_price'];
                }
            }
        }

        $total['discount_formated'] = price_format($total['discount'], false);

        /* 税额 */
        if (!empty($order['need_inv']) && $order['inv_type'] != '') {
            /* 查税率 */
            $rate = 0;
            $invoice_type = C('invoice_type');
            foreach ($invoice_type['type'] as $key => $type) {
                if ($type == $order['inv_type']) {
                    $rate = floatval($invoice_type['rate'][$key]) / 100;
                    break;
                }
            }
            if ($rate > 0) {
                $total['tax'] = $rate * $total['goods_price'];
            }
        }
        $total['tax_formated'] = price_format($total['tax'], false);

        /* 包装费用 */
        if (!empty($order['pack_id'])) {
            $total['pack_fee'] = D('Cart')->pack_fee($order['pack_id'], $total['goods_price']);
        }
        $total['pack_fee_formated'] = price_format($total['pack_fee'], false);

        /* 贺卡费用 */
        if (!empty($order['card_id'])) {
            $total['card_fee'] = D('Cart')->card_fee($order['card_id'], $total['goods_price']);
        }
        $total['card_fee_formated'] = price_format($total['card_fee'], false);

        /* 红包 */
        if (!empty($order['bonus_id'])) {
            $bonus = D('Cart')->bonus_info($order['bonus_id']);
            $total['bonus'] = $bonus['type_money'];
        }
        $total['bonus_formated'] = price_format($total['bonus'], false);

        /* 线下红包 */
        if (!empty($order['bonus_kill'])) {
            $bonus = D('Cart')->bonus_info(0, $order['bonus_kill']);
            $total['bonus_kill'] = $order['bonus_kill'];
            $total['bonus_kill_formated'] = price_format($total['bonus_kill'], false);
        }

        /* 配送费用 */
        $shipping_cod_fee = NULL;

        if ($order['shipping_id'] > 0 && $total['real_goods_count'] > 0) {
            $region['country'] = $consignee['country'];
            $region['province'] = $consignee['province'];
            $region['city'] = $consignee['city'];
            $region['district'] = $consignee['district'];
            $shipping_info = D('Shipping')->shipping_area_info($order['shipping_id'], $region);

            if (!empty($shipping_info)) {
                if ($order['extension_code'] == 'group_buy') {
                    $weight_price =D('Cart')->cart_weight_price($order['user_id'],CART_GROUP_BUY_GOODS);
                } else {
                    $weight_price = D('Cart')->cart_weight_price($order['user_id']);
                }

                // 查看购物车中是否全为免运费商品，若是则把运费赋为零
                $sql = 'SELECT count(*) as count FROM ' . C('DB_PREFIX') . "cart WHERE  `user_id` = '" . $order['user_id'] . "' AND `extension_code` != 'package_buy' AND `is_shipping` = 0 limit 1";

                $res = $Model->query($sql);
                $res =$res[0];
                $shipping_count = $res['count'];

                $total['shipping_fee'] = ($shipping_count == 0 AND $weight_price['free_shipping'] == 1) ? 0 : shipping_fee($shipping_info['shipping_code'], $shipping_info['configure'], $weight_price['weight'], $total['goods_price'], $weight_price['number']);

                if (!empty($order['need_insure']) && $shipping_info['insure'] > 0) {
                    $total['shipping_insure'] = shipping_insure_fee($shipping_info['shipping_code'], $total['goods_price'], $shipping_info['insure']);
                } else {
                    $total['shipping_insure'] = 0;
                }

                if ($shipping_info['support_cod']) {
                    $shipping_cod_fee = $shipping_info['pay_fee'];
                }
            }
        }

        $total['shipping_fee_formated'] = price_format($total['shipping_fee'], false);
        $total['shipping_insure_formated'] = price_format($total['shipping_insure'], false);

        // 购物车中的商品能享受红包支付的总额
        $bonus_amount = D('Cart')->compute_discount_amount($order['user_id']);
        // 红包和积分最多能支付的金额为商品总额
        $max_amount = $total['goods_price'] == 0 ? $total['goods_price'] : $total['goods_price'] - $bonus_amount;

        /* 计算订单总额 */
        if ($order['extension_code'] == 'group_buy' && $group_buy['deposit'] > 0) {
            $total['amount'] = $total['goods_price'];
        } else {
//            $total['amount'] = $total['goods_price'] - $total['discount'] + $total['tax'] + $total['pack_fee'] + $total['card_fee'] +
//            $total['shipping_fee'] + $total['shipping_insure'] + $total['cod_fee'];
//            添加折扣减去金额
            $total['amount'] = $total['goods_price'] - $total['discount'] + $total['tax'] + $total['pack_fee'] + $total['card_fee'] + $total['shipping_fee'] + $total['shipping_insure'] + $total['cod_fee'];

            // 减去红包金额
            $use_bonus = min($total['bonus'], $max_amount); // 实际减去的红包金额
            if (isset($total['bonus_kill'])) {
                $use_bonus_kill = min($total['bonus_kill'], $max_amount);
                $total['amount'] -= $price = number_format($total['bonus_kill'], 2, '.', ''); // 还需要支付的订单金额
            }

            $total['bonus'] = $use_bonus;
            $total['bonus_formated'] = price_format($total['bonus'], false);

            $total['amount'] -= $use_bonus; // 还需要支付的订单金额
            $max_amount -= $use_bonus; // 积分最多还能支付的金额
        }

        /* 余额 */
        $order['surplus'] = $order['surplus'] > 0 ? $order['surplus'] : 0;
        if ($total['amount'] > 0) {
            if (isset($order['surplus']) && $order['surplus'] > $total['amount']) {
                $order['surplus'] = $total['amount'];
                $total['amount'] = 0;
            } else {
                $total['amount'] -= floatval($order['surplus']);
            }
        } else {
            $order['surplus'] = 0;
            $total['amount'] = 0;
        }
        $total['surplus'] = $order['surplus'];
        $total['surplus_formated'] = price_format($order['surplus'], false);

        /* 积分 */
        $order['integral'] = $order['integral'] > 0 ? $order['integral'] : 0;
        if ($total['amount'] > 0 && $max_amount > 0 && $order['integral'] > 0) {
            $integral_money = value_of_integral($order['integral']);

            // 使用积分支付
            $use_integral = min($total['amount'], $max_amount, $integral_money); // 实际使用积分支付的金额
            $total['amount'] -= $use_integral;
            $total['integral_money'] = $use_integral;
            $order['integral'] = integral_of_value($use_integral);
        } else {
            $total['integral_money'] = 0;
            $order['integral'] = 0;
        }
        $total['integral'] = $order['integral'];
        $total['integral_formated'] = price_format($total['integral_money'], false);

        /* 保存订单信息 */
        $_SESSION['flow_order'] = $order;

        $se_flow_type = isset($_SESSION['flow_type']) ? $_SESSION['flow_type'] : '';

        /* 支付费用 */
        if (!empty($order['pay_id']) && ($total['real_goods_count'] > 0 || $se_flow_type != CART_EXCHANGE_GOODS)) {
            $total['pay_fee'] = pay_fee($order['pay_id'], $total['amount'], $shipping_cod_fee);
        }

        $total['pay_fee_formated'] = price_format($total['pay_fee'], false);
        $total['amount'] += $total['pay_fee']; // 订单总额累加上支付费用
        $total['amount_formated'] = price_format($total['amount'], false);

        /* 取得可以得到的积分和红包 */
        if ($order['extension_code'] == 'group_buy') {
            $total['will_get_integral'] = $group_buy['gift_integral'];
        } elseif ($order['extension_code'] == 'exchange_goods') {
            $total['will_get_integral'] = 0;
        } else {
            $total['will_get_integral'] = D('Cart')->get_give_integral($goods,$order['user_id']);
        }

//        折扣满减价格
        $total['formated_discount_price'] = $total['market_price_formated'] - $total['goods_price'];
        $total['will_get_bonus'] = $order['extension_code'] == 'exchange_goods' ? 0 : price_format(D('Cart')->get_total_bonus($order['user_id']), false);
        $total['formated_goods_price'] = price_format($total['goods_price'], false);
        $total['formated_market_price'] = price_format($total['market_price'], false);
        $total['formated_saving'] = price_format($total['saving'], false);

        if ($order['extension_code'] == 'exchange_goods') {
            $sql = 'SELECT SUM(eg.exchange_integral) ' .
                'as sum FROM ' . C('DB_PREFIX') . 'cart AS c,' . C('DB_PREFIX') . 'exchange_goods AS eg ' .
                "WHERE c.goods_id = eg.goods_id AND c.session_id= '" . SESS_ID . "' " .
                "  AND c.rec_type = '" . CART_EXCHANGE_GOODS . "' " .
                '  AND c.is_gift = 0 AND c.goods_id > 0 ' .
                'GROUP BY eg.goods_id limit 1';
            $res = $Model->query($sql);
            $res = $res[0];
            $exchange_integral = $res['sum'];
            $total['exchange_integral'] = $exchange_integral;
        }

        return $total;
    }


    /**
     * 修改订单
     * @param   int     $order_id   订单id
     * @param   array   $order      key => value
     * @return  bool
     */
    public function update_order($order_id, $order) {
        $this->table = 'order_info';
        $condition['order_id'] = $order_id;
        $sql='select * from '.C('DB_PREFIX').'order_info where order_id='.$order_id;
        $Model=new Model();
        $res =$Model->query($sql);
        $field_names[] = $res[0];
        //$res = $this->query('DESC ' . $this->pre . $this->table);
        /*
         while ($row = mysql_fetch_row($res)) {
         $field_names[] = $row[0];
         */
        foreach ($field_names as $value) {
            if (array_key_exists($value, $order) == true) {
                $order_info[$value] = $order[$value];
            }
        }

        if($order['pay_status'] == PS_PAYED){
            A("Smsapi")->send_message_api('order_pay_ok',$order['mobile'],$order['consignee'],'',$order['order_sn'],'',session('user_id'));
        }

        return M('order_info')->where($condition)->save($order_info);
    }

    /**
     * 获取用户默认地址的GPS坐标值
     * Author:何锐 <poptser@foxmail.com>
     * @param $uid
     * @return bool|void
     */
    public function get_user_default_address_gps($uid){
        $where['user_id'] = $uid;
        $where['default'] = 1;
        $user_address_id = M("user_address")->where($where)->getField('address_id');
        if ($user_address_id){
            $data = $this->get_address_by_id($user_address_id);
            $data['gps'] = address_to_gps_amap($data['all_address'],$data['city']);
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 根据ID查询详细地址
     * Author:何锐 <poptser@foxmail.com>
     * @param $address_id
     * @return bool|string
     */
    public function get_address_by_id($address_id){
        $user_address = M("user_address")->where('address_id ='.$address_id)->order('province,city,district,address')->find();
        if($user_address){
            $province = M('region')->where('region_id ='.$user_address['province'])->getField('region_name');
            $city = M('region')->where('region_id ='.$user_address['city'])->getField('region_name');
            $district = M('region')->where('region_id ='.$user_address['district'])->getField('region_name');

            $building_address = $province.$city.$district.$user_address['sign_building'];
            $all_address = $province.$city.$district.$user_address['address'];
            $data['all_address'] = str_replace(' ','',$all_address);
            $data['province'] = $province;
            $data['city'] = $city;
            $data['district'] = $district;
            $data['building_address'] = str_replace(' ','',$building_address);
            $data['lit_address'] = $user_address['address'];
            $data['is_ok'] = $user_address['is_ok'];

            $data['longitude'] = $user_address['longitude'];
            $data['latitude'] = $user_address['latitude'];
            $data['sign_building'] = $user_address['sign_building'];
            $data['address_building'] = $user_address['address'].$user_address['sign_building'];
            $data['district'] = $district;
            $data['district_id'] = $user_address['district'];
            return $data;
        }else{
            return false;
        }
    }
    /**
     * 写入 用户记录
     * Author:何锐 <poptser@foxmail.com>
     */
    public function write_user_action($name,$user_id,$type,$old_value,$new_value){
        $data['action_name'] = $name;       //操作者用户名
        $data['action_time'] = gmtime();    //操作时间
        $data['action_type'] = $type;       //操作类型
        $data['old_value'] = $old_value;    //原来值
        $data['new_value'] = $new_value;    //新值
        $data['user_id'] = $user_id;        //用户ID
        M('user_action')->add($data);
    }

    /**
     * 获取秒杀通知会员详细信息
     * Created by Jerry
     * @param $user_id
     * @return mixed
     */
    public function findBuyNowUserInfo($user_id)
    {
        $where = array(
            'u.user_id'		=>	$user_id,
            'ua.default'	=>	1,
        );

        $field = 'u.user_id, u.user_name, u.mobile_phone, u.user_rank, ua.consignee, ua.mobile';

        return $this->alias('u')
            ->field($field)
            ->join('LEFT JOIN __USER_ADDRESS__ AS ua ON u.user_id = ua.user_id')
            ->where($where)
            ->find();



//		return $this->field($field)->where($where)->find();
    }


    /**
     * 获取用户手机号码
     * Created by Jerry
     * @param $user_id
     * @return mixed
     */
    public function findBuyNowNoticeUserMobile($user_id)
    {
        $where = array(
            'user_id'	=>	$user_id,
        );

        return $this->where($where)->getField('mobile_phone');
    }

    /**
     * 返回一个指定用户等级的userId
     * Created by Jerry
     * @param $rank
     * @return bool|mixed
     */
    public function findUserByUserRank($rank)
    {
        if (empty($rank)) {
            return false;
        }

        $where = array(
            'user_rank'	=>	$rank,
        );

        $field = 'user_id';

        return $this->field($field)->where($where)->find();
    }



    /**
     * 根据配送区域 获取可配送的时间段
     * @param null $mode
     * @param int $wdr_id
     * @return array
     */
    public function distributie_time_list_new($mode = null, $wdr_id=0){
        if(empty($mode)){
            $distribution_time_array['tomorrow'] =array();
            $distribution_time_array['today'] =array();
            return $distribution_time_array;
        }
        //mode_id 6 39 当日达区域
        $distribution_time_array = array();

        $distribution_time =  M("distribution_time")->field("id,start_time,end_time,closing_time")
            ->where(array("mode_id"=>$mode))->order("start_time asc")->select();
//        var_dump($distribution_time);die;
        if(empty($distribution_time)){
            //未找到此配送区域，返回为空
            $distribution_time_array['tomorrow'] =array();
            $distribution_time_array['today'] =array();
            return $distribution_time_array;
        }

        


        $distribution_mode =  M("distribution_mode")->where(array("id"=>$mode))->getField("arrival_type");

        //获取负卖配送时间
        $distribution_time_new=$this->get_delivery_time_for_negative_to_sell($distribution_time);
        if($distribution_time_new!==false){
            $distribution_time=$distribution_time_new;
            if(date("H")>"07"){
                $distribution_mode=1;
            }
        }

        /**
         * 处理区域配送时间订单峰值、是否超时免单处理
         * Created By caicm
         */
        if($wdr_id){
            $distribution_model = new OrderDistributionTimeService();
            return $distribution_model->get_distributie_time($distribution_time, $distribution_mode, $wdr_id );
        }

        //今日配送时间
        if($distribution_mode==1){
            //次日达区域，只显示今天配送去为空
            $distribution_time_array['today'] =array();
        }else{
            //今日达区域，显示今天和明天
            foreach ($distribution_time as $value){
                $closing_time = str_replace(":","",$value['closing_time']);
                $start_time = str_replace(":","",$value['start_time']);
                $now_hour = date('H',time()).date('i',time());
                if ($closing_time > $now_hour && $start_time > $closing_time) {
                    $distribution_time_array['today'][] = array(
                        "value" =>strtotime(date("Y-m-d",time())." ".$value['start_time'].":00")."-".strtotime(date("Y-m-d",time())." ".$value['end_time'].":00"),
                        "title" =>"今日 {$value['start_time']} - {$value['end_time']}",
                        'closing'	=>	"今日 {$value['closing_time']}",
                    );
                }
                //dump($closing_time."--".$now_hour."--".$start_time);
                if ($closing_time > $now_hour && $start_time < $closing_time) {
                    //开始时间大于截单时间，将时间定位次日
                    $distribution_time_array['tomorrow'][] = array(
                        "value" =>strtotime(date("Y-m-d",strtotime("+1 day"))." ".$value['start_time'].":00")."-".strtotime(date("Y-m-d",strtotime("+1 day"))." ".$value['end_time'].":00"),
                        "title" =>"明日 {$value['start_time']} - {$value['end_time']}",
                        'closing'	=>	"今日 {$value['closing_time']}",
                    );
                }
            }
            if(empty($distribution_time_array['today'])){
                $distribution_time_array['today'] =array();
            }
        }
        //明天配送时间
        foreach ($distribution_time as $value){
            $closing_time = str_replace(":","",$value['closing_time']);
            $start_time = str_replace(":","",$value['start_time']);
            if($start_time>$closing_time){
                $distribution_time_array['tomorrow'][] = array(
                    "value" =>strtotime(date("Y-m-d",strtotime("+1 day"))." ".$value['start_time'].":00")."-".strtotime(date("Y-m-d",strtotime("+1 day"))." ".$value['end_time'].":00"),
                    "title" =>"明日 {$value['start_time']} - {$value['end_time']}",
                    'closing'	=>	"明日 {$value['closing_time']}",
                );
            }
        }

        $distribution_time_array['today_title'] = '当天送达';
        $distribution_time_array['tomorrow_title'] = '次日送达';
        return $distribution_time_array;
    }

    /**
     * Created by Jerry
     * @param int $mode
     * @return array|bool
     */
    public function user_address_distributie_time($mode = 0)
    {
        if (empty($mode)) {
            return false;
        }
        //mode_id 6 39 当日达区域
        $distribution_time_array = array();

        $distribution_time = M("distribution_time")->field("start_time,end_time,closing_time,closing_time")
            ->where(array("mode_id" => $mode))->order("closing_time asc")->select();

        if (empty($distribution_time)) {
            //未找到此配送区域，返回为空
            $distribution_time_array['tomorrow'] = array();
            $distribution_time_array['today'] = array();
            return $distribution_time_array;
        }


        $distribution_mode = M("distribution_mode")->where(array("id" => $mode))->getField("arrival_type");

        //今日配送时间
        if ($distribution_mode == 1) {
            //次日达区域，只显示今天配送去为空
            $distribution_time_array['today'] = array();
        } else {
            //今日达区域，显示今天和明天
            foreach ($distribution_time as $value) {
                $closing_time = str_replace(":", "", $value['closing_time']);
                $now_hour = date('H', time()) . date('i', time());
                if ($closing_time > $now_hour) {
                    $distribution_time_array['today'][] = array(
                        "value" => strtotime(date("Y-m-d", time()) . " " . $value['start_time'] . ":00") . "-" . strtotime(date("Y-m-d", time()) . " " . $value['end_time'] . ":00"),
                        "title" => "今日 {$value['start_time']} - {$value['end_time']}",
                        'closing'	=>	"今日 {$value['closing_time']}",
                    );
                }
            }

            if (empty($distribution_time_array['today'])) {
                $distribution_time_array['today'] = array();
            }
        }
        //明天配送时间
        foreach ($distribution_time as $value) {
            $distribution_time_array['tomorrow'][] = array(
                "value" => strtotime(date("Y-m-d", strtotime("+1 day")) . " " . $value['start_time'] . ":00") . "-" . strtotime(date("Y-m-d", strtotime("+1 day")) . " " . $value['end_time'] . ":00"),
                "title" => "明日 {$value['start_time']} - {$value['end_time']}",
                'closing'	=>	"明日 {$value['closing_time']}",
            );
        }

        return $distribution_time_array;
    }

    /**
     * Created by Jerry
     * @param int $uid
     * @param int $location
     * @param int $long
     * @param int $lati
     * @return mixed
     */
    public function get_goods_info_address_time($uid = 0, $location = 0, $long = 0, $lati = 0)
    {
        $longitude = $long;
        $latitude = $lati;
        $user_id = $uid;
        $hand = $location;
        if (empty($user_id)) {
            $hand = true;//无用户ID  使用定位参数
        }

        if ($hand) {
            if ($long && $lati) {
                $address = gps_to_address($longitude, $latitude);
                $address_gps['longitude'] = $longitude;
                $address_gps['latitude'] = $latitude;
            } else {
                returnApiError('经纬度参数错误');
            }
        } else {
            $address = $this->get_default_address($user_id);
            if(empty($address)){
                $address_gps['longitude'] = $longitude;
                $address_gps['latitude'] = $latitude;
                $address = gps_to_address($longitude,$latitude);
            }else{
                $address_gps = address_to_gps_amap($address['all_address'],$address['city']);
                $distribution_data['sign_building'] = $address['sign_building'];
            }
        }

        $distribution_data = $this->get_distribution_by_gps($address_gps['latitude'],$address_gps['longitude']);
        $distribution_data['dis_time'] = $this->distributie_time_list_new($distribution_data['mode_id']);
        $distribution_data['all_address'] = $address['all_address'];
        $distribution_data['lit_address'] = $address['lit_address'];

        if ($distribution_data) {
            $distribution_data['return'] = 1;
        } else {
            $distribution_data['return'] = 0;
        }

        if ($hand == 0 && $address['id']) {
            $distribution_data['address_id'] = $address['id'];
        } else {
            $distribution_data['address_id'] = 0;
        }

        return $distribution_data;
    }

    /**
     * 生成收货验证码
     * @param null $order_id
     * @return mixed|string
     */
    public function get_order_receipt_code($order_id=null){
        //生成收货验证码
        if(empty($order_id)){
            $order_id = I("post.order_id");
        }
        if(empty($order_id)){
            returnApiError("订单ID为空");
        }

        $order_verif_code = M('order_verif_code');
        $verif_code = $order_verif_code->where(array("order_id"=>$order_id))->getField("code");
        if($verif_code){
            return $verif_code;
        }else{
            $ver_code = getSmsCode();
            $sms_data['order_id'] = $order_id;
            $sms_data['code'] = $ver_code;
            M("order_verif_code")->add($sms_data);
            return $ver_code;
        }
    }

    /**
     * @role 获取负卖配送时间
     * @author Jianhe
     * @param $distribution_time
     * @return array|bool
     */
    private function get_delivery_time_for_negative_to_sell($distribution_time)
    {
        $distribution_time_new = array();
        $distribution_time_new1 = array();
        $uid = I("post.uid");
        $delivery_time_for_negative_to_sell = S('u' . $uid . '_delivery_time_for_negative_to_sell');
        S('u' . $uid . '_delivery_time_for_negative_to_sell', NULL);
        if ($delivery_time_for_negative_to_sell) {
            $delivery_time_for_negative_to_sell=explode("#",$delivery_time_for_negative_to_sell);
            $delivery_time_for_negative_to_sell_start_time=$delivery_time_for_negative_to_sell[0];
            $delivery_time_for_negative_to_sell_end_time=$delivery_time_for_negative_to_sell[1];

            foreach ($distribution_time as $oldTime) {
                if ($delivery_time_for_negative_to_sell_start_time <= $oldTime['start_time'] && $oldTime['end_time'] <= $delivery_time_for_negative_to_sell_end_time && !in_array($oldTime['start_time'].'__'.$oldTime['end_time'],$distribution_time_new1)) {
                    $distribution_time_new1[] = $oldTime['start_time'].'__'.$oldTime['end_time'];
                    $distribution_time_new[] = $oldTime;
                }
            }

            return $distribution_time_new;
        }

        return false;
    }

}